<?php

class EPrefichasDatosAlumnosController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/** 
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */ 
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','anio','create','admin','autocompleteTest','especialidadTest','dynamicestados','dynamicmunicipios'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		// Uncomment the following line if AJAX validation is needed
                $this->performAjaxValidation($model);
                $model=new Aspirante();

               //$this->folio;
                //$this->anio($model2);
		//echo var_dump($this->anio($model2));
                //$this->folio($model1);
                //$model->nombre_alumno='PF';
                //
                //LLAMADAS A LAS FUNCIONES DE LA TABLA E_PrefichasDetalle
                //$this->mas($model0);
                //$this->folio($model1);
                $this->anio($model2);
                $this->periodo($model3);
                //$this->numero($model4);
                $this->ipadd($model5);
                //$this->password($model6);
                $this->fechasol($model7);
                $this->fechaact($model8);
                $this->tipalumno($model9);
                //$this->ficha($model10);
                $this->status($model11);
                //$this->password($model6);
                //$this->folio($model1);
		if(isset($_POST['Aspirante']))
		{
                         $model->attributes=$_POST['Aspirante'];
                         $this->mail($correo_e);
                         //echo "<pre>";
                         //print_r($model->attributes);
                         //$comando -> execute();
                         //echo "</pre>";
			if($model->save())
                        {
                                echo "yaaaaa";
                                Yii::app()->user->setFlash('notice','Se guardaron los datos ¡¡Satisfactoriamente.!!');
				$this->redirect(array('view','id'=>$model->preficha));
                        }
                          else
                        {
                            Yii::app()->user->setFlash('error','Lo sentimos, existe algun error, vuelve a intentarlo.');
                        }
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}
        
        public function folio($model1)
         {
            //folio preficha
            $model1 = new EPrefichasDetalle();
//            $sql1="SELECT max(numero_preficha) FROM EPrefichasDetalle";
//            $comando1 =Yii::app() -> db -> createCommand($sql1)->queryScalar(); 
//
//            $sql2="select replace((cast(( $comando1 *.001) as char(5))),'.','')";
//            $comando2 =Yii::app() -> db -> createCommand($sql2)->queryScalar();
//            //    echo "<pre>";
//            //    echo 'numero generado';
//            //    print_r($comando2);
//            //    $comando -> execute();
//            //    echo "</pre>"; 
//            $sql3="SELECT ano FROM EPrefichasDetalle";
//            $comando3 =Yii::app() -> db -> createCommand($sql3)->queryAll();
            
            $model1->preficha='001'; 
             $model1->save();
            echo "folio";
         }

        public function anio($model2){ 
           //echo "holqqq";
           $model2=new Aspirante();
           $sdate=date("y");
           $model2->ano=$sdate;
               
           $model2->save();
       }
        
        public function periodo($model3){
            $model3=new Aspirante();
            $model3->periodo='2';
            echo "periodo";
        }
        
        public function numero($model4){
            $model4=new Aspirante();
            $sql3="SELECT max(numero_preficha) FROM Aspirante";
            $comando3 =Yii::app() -> db -> createCommand($sql3)->queryScalar(); 
                echo "<pre>";
                echo 'numero max de la bd anteriormente';
		print_r($comando3);
		//$comando -> execute();
		echo "</pre>";	
            $d=$comando3+1;
            $sql="insert into Aspirante(numero_preficha) values('$d')";
            $comando=Yii::app() -> db -> createCommand($sql)->queryAll();
                echo "<pre>";
                echo 'numero insertado en la bd';
		print_r($d);            

		//$comando -> execute();
		echo "</pre>";	
                $model4->numero_preficha=$comando;
//            $sql2="select replace((cast(( $comando3 *.001) as char(5))),'.','')";
//            $comando2 =Yii::app() -> db -> createCommand($sql2)->queryScalar();
//                echo "<pre>";
//                echo 'numero generado';
//		print_r($comando2);
//		//$comando -> execute();
//		echo "</pre>";    
                echo "numero";
        }
        
        
        public function ipadd($model5)
        {
            $model5=new EPrefichasDetalle();
            if(!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
            {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
                // IP compartido
                echo "IP Share: " . $_SERVER['HTTP_CLIENT_IP'] . "<br />";
            }
            elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   	//to check ip is pass from proxy
            {   
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                // IP Proxy
                echo "IP Proxy: " . $_SERVER['HTTP_X_FORWARDED_FOR'] . "<br />";
            }
            else
                $ip = $_SERVER['REMOTE_ADDR'];
                // IP Acceso
                echo "IP Access: " . $_SERVER['REMOTE_ADDR'] . "<br />";
            //return $ip;
            $model5->ip=$ip;
            echo "ipadd";
         }
	
         public function password($model6){
             $model6=new EPrefichasDetalle();
              $keychars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
              $length = 6;
              // RANDOM KEY GENERATOR
              $randkey = "";
              $max=strlen($keychars)-1;
              for ($i=0;$i<$length;$i++) 
              {
                   $randkey .= substr($keychars, rand(0, $max), 1);
                   $model6->clave=$randkey;                   
              } 
              $med5=md5($randkey);
              $med6=$randkey;
              $model6->contrasena=$med5;
              $model6->contrasena_desc=$med6;
              
              echo "$model6";
              echo "password";
         }
         
         public function fechasol($model7){
             $model7=new Aspirante();
             $sdate2=date("d-m-Y H:i:s");
             $model7->fecha_solicitud=$sdate2;
             echo "fechasol";
         }
         
         public function fechaact($model8){
             $model8=new Aspirante();
             $sdate3=date("d-m-Y H:i:s");
             $model8->fecha_actulizacion=$sdate3;
             echo "fechaact";
         }
         
         public function tipalumno($model9){
             $model9=new Aspirante();
             $model9->tipo_alumno='LI';
             echo "tipalumno";
         }
               
         public function ficha($model10)
         {
            $model10 = new EPrefichasDetalle();
            $sql7="SELECT max(numero_preficha) FROM EPrefichasDetalle";
            $comando7 =Yii::app() -> db -> createCommand($sql7)->queryScalar(); 
            
            $sql8="select replace((cast(( $comando7 *.001) as char(5))),'.','')";
            $comando8 =Yii::app() -> db -> createCommand($sql8)->queryScalar();
            
            $sql9="SELECT anio FROM EPrefichasDetalle";
            $comando9 =Yii::app() -> db -> createCommand($sql9)->queryScalar();
            
            $model10->ficha='PF'."$comando8"."$comando9";
            //          $sdate=date("y");
            //	        $model=new Gen;
            //	        $model->preficha='PF'."$sdate";
            //                
            //                $sql2="SELECT max(numero) FROM num";
            //		$comando2 =Yii::app() -> db -> createCommand($sql2)->queryScalar();
            //		echo "<pre>";
            //		print_r($comando2);
            //		//$comando -> execute();
            //		echo "</pre>";	
            //		
            //		$d="00".$comando2;
            //		echo $d;
            //		//die();
            //		$sql="insert into E_PrefichasDetalle(ano) values('$d'+001)";
            //		$comando=Yii::app() -> db -> createCommand($sql)->queryAll();
            echo "ficha";
         }
             
        public function status($model11){
            $model11=new EPrefichasDetalle();
            $model11->id_prefichas_statu='1';
            echo "status";
        } 
        
        public function mail($correo_e)
        {
               $model12=new EPrefichasDetalle();
                include("class.phpmailer.php");
                include("class.smtp.php");
                            
                $keychars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
                $length = 6;
                // RANDOM KEY GENERATOR
                $randkey = "";
                $max=strlen($keychars)-1;
                for ($i=0;$i<$length;$i++) {
                    $randkey .= substr($keychars, rand(0, $max), 1);
                    $model12->contrasena_desc=$randkey;                   
                } 
                $med5=md5($randkey);
                $model12->contrasena=$med5;
                           
                
            //empieza programacion para mandar e-mail              	

                    $correo_e = 'nan23m@gmail';
                    $mail = new PHPMailer();
                    $mail->IsSMTP();
                    $mail->SMTPAuth = true;
                    $mail->SMTPSecure = "ssl";
                    $mail->Host = "smtp.gmail.com";
                    $mail->Port = 465;
                    $mail->Username = "";
                    $mail->Password = "";

                    $mail->From = $correo_e;
                    $mail->FromName = "Instituto Tecnologico de Celaya";
                    $mail->Subject = "Envio de password preficha.";
                    $mail->MsgHTML("
                           <p> Nombre Usuario: </p>
                           <p> SU PASSWORD DE PREFICHA ES: $randkey </p>
                           "); 
                                     
                    $mail->AddAttachment("-");
                    $mail->AddAttachment("-");

                    $mail->AddAddress($correo_e,"Reuni&oacute;n Egresados.");
                    $mail->IsHTML(true);

                    if(!$mail->Send()) {
                        
                    } else {
                       return "Mensaje enviado correctamente";
                        
                    }
                    $mail->Body = $this->render ("emailConfirmation", array(),true);
                    echo "mail";
        }
         
        
        
        
        public function actionAutocompleteTest() {
	    $res =array(); 
	    if (isset($_GET['term'])) {
	        //$qtxt ="SELECT username FROM {{user}} WHERE username LIKE :username";
                $qtxt ="select clavecct from \"E_escuelaProcedencia\" WHERE clavecct LIKE :clavecct";
	        $command =Yii::app()->db->createCommand($qtxt);
                //STRTOUPPER ACEPTAR MAYUSCUAS Y MINUSCULAS
	        $command->bindValue(":clavecct", '%'.strtoupper($_GET['term']).'%', PDO::PARAM_STR);
	        //$res =$command->queryColumn(); queryAll
		$res =$command->queryColumn(); 
	    }
	    echo CJSON::encode($res);
	    Yii::app()->end();
	}
        
       public function actionDynamicestados(){
            $data=XEstados::model()->findAll('id_pais=:id_pais', 
            array(':id_pais'=>$_POST['Pais']));
                $data=CHtml::listData($data,'id_estado','desc_estado');
                echo CHtml::tag('option',
                array('value'=>''),'Seleccione un Estado',true);
                
                    foreach($data as $value=>$name){
                        echo CHtml::tag('option',
                        array('value'=>$value),CHtml::encode($name),true);
                    }
        }    

        public function actionDynamicmunicipios(){ 
            $data=XMunicipios::model()->findAll('id_estado=:id_estado', 
            array(':id_estado'=>$_POST['Estados']));
            echo CHtml::tag('option',
            array('value'=>''),'Seleccione un Municipio',true);       
            $data=CHtml::listData($data,'id_municipio','desc_mun');
                foreach($data as $value=>$name){
                    echo CHtml::tag('option',
                    array('value'=>$value),CHtml::encode($name),true);
                }
        }
          
        
         
        /*
           public function actionEspecialidadTest() {
	    $res =array(); 
	    if (isset($_GET['term'])) {
	        //$qtxt ="SELECT username FROM {{user}} WHERE username LIKE :username";
                $qtxt ="select \"dscEspecialidad\" , \"cveEspecialidad\" from \"E_especialidad\" WHERE \"dscEspecialidad\" LIKE :dscEspecialidad";
	        $command =Yii::app()->db->createCommand($qtxt);
                //STRTOUPPER ACEPTAR MAYUSCUAS Y MINUSCULAS
	        $command->bindValue(":dscEspecialidad", '%'.strtoupper($_GET['term']).'%', PDO::PARAM_STR);
	        //$res =$command->queryColumn(); queryAll
		$res =$command->queryColumn(); 
	    }
	    echo CJSON::encode($res);
	    Yii::app()->end();
	}
         */
        
        
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['EPrefichasDatosAlumnos']))
		{
			$model->attributes=$_POST['EPrefichasDatosAlumnos'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->preficha));
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('EPrefichasDatosAlumnos');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new EPrefichasDatosAlumnos('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['EPrefichasDatosAlumnos']))
			$model->attributes=$_GET['EPrefichasDatosAlumnos'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=EPrefichasDatosAlumnos::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
          
		if(isset($_POST['ajax']) && $_POST['ajax']==='eprefichas-datos-alumnos-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
